﻿/*
 * Created by SharpDevelop.
 * Date: 21.10.2011
 * Time: 13:00
 * 
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CaesarCoder
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		Config config;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			this.cbAction.Text = "Encode";
			this.cbTable.SelectedItem = "Verifying tables...";
		}
		
		/// <summary>
		/// string to indicate that no (valid) Conversion Tables have been found
		/// </summary>
		string errorNoConversionTables = "Error! No valid Conversion tables found.";
		string errorNA = "N/A";
		
		void inputChanged()
		{
			this.btnStart.Enabled = this.validInput();
		}
		
		/// <summary>
		/// Indicates if Input data is sufficient to initiate a encoding/decoding operation
		/// </summary>
		bool validInput()
		{
			return ( (this.tbSource.Text.Length > 0) && (this.tbTarget.Text.Length > 0) &&
			        (!this.cbTable.Text.Equals(this.errorNA)) );
		}
		
		// the default dir to search for a file to open or save
		string defaultDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
		
		/// <summary>
		/// Clears the text of the Status Label
		/// </summary>
		void clearStatusLabel()
		{
			this.statusLabel1.Text = "";
		}
		
		void browse_source(object sender, EventArgs e)
		{
			OpenFileDialog openSourceFileDialog = new OpenFileDialog();
			
			openSourceFileDialog.Title = "Open File...";
			openSourceFileDialog.InitialDirectory = defaultDir;
			openSourceFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
			openSourceFileDialog.FilterIndex = 1;
			openSourceFileDialog.RestoreDirectory = true;

			if(openSourceFileDialog.ShowDialog() == DialogResult.OK)
			{
				this.defaultDir = openSourceFileDialog.FileName.Substring(0, openSourceFileDialog.FileName.LastIndexOf('\\'));
				this.tbSource.Text = openSourceFileDialog.FileName;
			}
		}
		
		void browse_target(object sender, EventArgs e)
		{
			SaveFileDialog saveTargetFileDialog = new SaveFileDialog();
			
			saveTargetFileDialog.Title = "Save As...";
			saveTargetFileDialog.InitialDirectory = defaultDir;
			saveTargetFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
			saveTargetFileDialog.FilterIndex = 1;
			saveTargetFileDialog.RestoreDirectory = true;
			
			if(saveTargetFileDialog.ShowDialog() == DialogResult.OK)
			{
				this.tbTarget.Text = saveTargetFileDialog.FileName;
			}
		}
		
		void start_conversion(object sender, EventArgs e)
		{
			if (this.btnStart.Text == "ENCODE")
			{
				if (this.config.ConversionTables[this.cbTable.SelectedIndex].EncryptFile(this.tbSource.Text, this.tbTarget.Text) == true)
				{
					MessageBox.Show("File successfully encrypted and saved to '" + this.tbTarget.Text + "'", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
				} else {
					MessageBox.Show("Could not encrypt '" + this.tbSource.Text + "'. Check if the file exists and whether you have the permissions to open it.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			} else {
				if (this.config.ConversionTables[this.cbTable.SelectedIndex].DecryptFile(this.tbSource.Text, this.tbTarget.Text) == true)
				{
					MessageBox.Show("File successfully decrypted and saved to '" + this.tbTarget.Text + "'", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
				} else {
					MessageBox.Show("Could not decrypt '" + this.tbSource.Text + "'. Check if the file exists and whether you have the permissions to open it.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
		
		void action_changed(object sender, EventArgs e)
		{
			this.inputChanged();
			this.btnStart.Text = this.cbAction.Text.ToUpper();
		}
		
		void filepath_changed(object sender, EventArgs e)
		{
			this.inputChanged();
			this.clearStatusLabel();
		}
		
		void show_manager(object sender, EventArgs e)
		{
			Form manager = new Manager("config", this.cbTable.SelectedIndex);
			//this.WindowState = FormWindowState.Minimized;
			manager.ShowDialog();
			//this.WindowState = FormWindowState.Normal;
			this.ReloadConfig();
		}
		
		void DataBind()
		{
			if (this.config != null && this.config.ConversionTables.Count > 0)
			{
				//set the combobox datasource to be the list of all Conversion Tables
				this.cbTable.DataSource = this.config.ConversionTables;
				this.cbTable.DisplayMember = "Name";
				this.cbTable.ValueMember = "Name";
				
				//set the Text property datasource to be the ctlist.Description field
				this.labelTableDescription.DataBindings.Add("Text", this.config.ConversionTables, "Description");
			}
			else 
			{
				this.cbTable.Items.Remove("Verifying tables...");
				this.cbTable.Text = this.errorNA;
				this.labelTableDescription.Text = this.errorNoConversionTables;
			}
		}
		
		void ReloadConfig()
		{
			this.config.Reload();
			// remove all bindings
			this.labelTableDescription.DataBindings.Clear();
			// databind the controls again
			this.DataBind();
		}
		
		void mainform_loaded(object sender, EventArgs e)
		{
			// load configuration
			this.config = new Config("config");
			this.DataBind();
		}
	}
}
